package com.atguigu.gulimall_product.product.service.impl;

import com.atguigu.gulimall_product.product.dao.CategoryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall_product.product.entity.CategoryEntity;
import com.atguigu.gulimall_product.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryDao categoryDao;
    CategoryEntity category;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public CategoryEntity getListWithTree() {
        category=new CategoryEntity();
        //第一步创建一个全局的Category类对象
        //第二步给category设置parentID为0,让他们根据parentId查询出一级分类
        category.setCatId(0L);
        //调用递归函数,查询出parentCid为0的所有子分类
        this.getChildList(category);
        //第三步查询出的所有一级分类设置到category的list属性中这个是重点,不需要返回,只需要设置属性,然后在根据这个对象就可以找到所有子分类了
        //递归即可
        return category;
    }

    @Override
    public void deleteByIds(Long catIds[]) {
        for (Long catId : catIds) {
            baseMapper.deleteById(catId);
            System.out.println(catId);
        }
    }

    public void getChildList(CategoryEntity category){
        List<CategoryEntity> categoryEntities = categoryDao.listByParentCid(category.getCatId());
        if(categoryEntities!=null){
        category.setChildren(categoryEntities);
        for (CategoryEntity entity : categoryEntities) {
            entity.setLabel(entity.getName());
            getChildList(entity);
        }
        }
    }
}